
// We need all the log functions visible so we set this to DEBUG

#import "CTLogging.h"
#import "BLEKiUtils.h"

#define SAVE_TIME       (15*24*60*60)       // 15天清理一次
#define kMaxFileSize    (1024 * 1024 * 7)   // 最大7M(因为日志上传时最多8M)

static int  AddLogFile(NSString *fname);
static int  logfd = 0;

static void AddStderrOnce() {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        asl_add_log_file(NULL, STDERR_FILENO);
        logfd = AddLogFile([BLEKiUtils getLogFilePath]);
    });
}

void _CTLog(int LEVEL, NSString *format, ...) {
       if ([BLEKiUtils isWriteLogEnable]) { //日志输出权限控制
           AddStderrOnce();
           
           va_list args;
           va_start(args, format);
           NSString *message = [[NSString alloc] initWithFormat:format arguments:args];
           asl_log(NULL, NULL, (LEVEL), "%s\n", [message UTF8String]);
           va_end(args);
       }
}

static int AddLogFile(NSString *fname) {
    int result = 1;
    int fd = -1;
    NSData *data = [NSData dataWithContentsOfFile:fname];
    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:fname error:NULL];
    NSDate *cd = attrs[@"NSFileCreationDate"];
    if (-[cd timeIntervalSinceNow] > SAVE_TIME) {
        printf("The file out of Date and delete the old file");
        [[NSFileManager defaultManager] removeItemAtPath:fname error:nil];
    }
    if ([data length] > kMaxFileSize) {
        printf("The file size overload and delete the old file");
        [[NSFileManager defaultManager] removeItemAtPath:fname error:nil];
    }
    fd = open([fname fileSystemRepresentation], (O_RDWR|O_CREAT|O_APPEND), (S_IRWXU|S_IRWXG|S_IRWXO));
    if (fd != -1) {
        result = asl_add_log_file(NULL, fd);
       	printf("AddLogFile %s (%d)\n", [fname fileSystemRepresentation], result);
    }
    return fd;
}




